<template>
  <div id="app" style="font-size: 26px; font-weght: bold; margin: 30px 0">
    <div class="all" v-if="allFlag">
      <header class="header">
        <div
          v-for="(item, index) in topInputList"
          :key="index"
          class="everyBox"
        >
          <span class="span">{{ item.title }}：</span>
          <el-input
            v-model="item.text"
            :placeholder="item.title"
            class="top-input"
          ></el-input>
        </div>
        <div style="margin-right: 20px">
          <span class="span">商品品牌</span>
          <el-select v-model="goods_brand_id" placeholder="请选择" clearable>
            <el-option
              v-for="item in brandOption"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
        <div style="margin-right: 20px">
          <span class="span">商品分类</span>
          <el-cascader
            v-model="goods_cat_id"
            :props="fenleiListProps"
            :options="fenleiList"
          ></el-cascader>
        </div>
        <div class="caozuo">
          <el-button type="primary" icon="el-icon-search" @click="search"
            >搜索</el-button
          >
          <el-button type="primary" @click="reset">重置</el-button>
          <el-button type="primary" icon="el-icon-plus" @click="addGood"
            >添加商品</el-button
          >
        </div>
      </header>
      <div class="body">
        <el-tabs type="border-card" @tab-click="handleClick">
          <el-tab-pane>
            <span label="全部商品" slot="label"
              >全部商品<i class="el-icon-date"></i>
            </span>
          </el-tab-pane>
          <el-tab-pane>
            <span label="上架商品" slot="label"
              >上架商品<i class="el-icon-date"></i>
            </span>
          </el-tab-pane>
          <el-tab-pane>
            <span label="下架商品" slot="label"
              >下架商品<i class="el-icon-date"></i>
            </span>
          </el-tab-pane>
          <el-tab-pane>
            <span label="库存报警" slot="label"
              >库存报警<i class="el-icon-date"></i>
            </span>
          </el-tab-pane>
          <el-table
            v-loading="loading"
            :data="tableData"
            max-height="600"
            border
            fit
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              width="55"
              fixed
            ></el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="id"
              label="ID"
              width="50"
            >
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="nickname"
              label="上下架"
              width=""
            >
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.marketable"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="上架"
                  inactive-text="下架"
                  :active-value="1"
                  :inactive-value="2"
                  @change="switchChange(scope.row)"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="mobile"
              label="缩略图"
              width="100"
            >
              <template slot-scope="scope">
                <el-image
                  style="width: 50px; height: 50px"
                  :src="scope.row.aimages[0]"
                  :preview-src-list="scope.row.aimages"
                  fit="cover"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="name"
              label="名称"
              width=""
            >
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="bn"
              label="商品编号"
              width=""
            >
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="brand_name"
              label="品牌"
              width=""
            >
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="cat_name"
              label="分类"
              width=""
            >
            </el-table-column>
            <el-table-column show-overflow-tooltip label="库存" width="">
              <template slot-scope="scope">
                <span :style="scope.row.stock <= 50 ? 'color:red' : ''">{{
                  scope.row.stock
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="price"
              label="销售价"
              width=""
            >
            </el-table-column>
            <el-table-column show-overflow-tooltip label="操作" width="">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleEdit(scope.$index, scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  @click="detailGoods(scope.$index, scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tabs>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40, 50, 60]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <div class="bianjiGoods" v-if="!allFlag && bianjiFlag">
      <bianjiGoods :sonObj="sonObj" @back="back"></bianjiGoods>
    </div>
    <div v-if="!allFlag && addFlag">
      <addGoods @back="back"></addGoods>
    </div>
  </div>
</template>
  
  <script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import {
  goodsList,
  up_down,
  deleteGoods,
  goodSort,
  brandList,
} from "../../../utils/api";
import bianjiGoods from "../../common/bianjimarketGoods";
import addGoods from "../../common/addmarketGoods";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    bianjiGoods,
    addGoods,
  },
  data() {
    //这里存放数据
    return {
      allFlag: true,
      bianjiFlag: false,
      addFlag: false,
      loading: true,
      token: sessionStorage.getItem("token"),
      topInputList: [
        { title: "商品名称", text: "" },
        { title: "商品编号", text: "" },
      ],
      goods_cat_id: "",
      goods_brand_id: "",
      fenleiListProps: {
        label: "name",
        value: "id",
        children: "child",
        emitPath: false,
      },
      fenleiList: [],
      brandOption: [],
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      total: 0,
      limit: 10,
      value1: "",
      value2: "",
      imgHeader: this.Global.imgHeader,

      options1: [
        {
          value: "111",
          label: "全部",
        },
        {
          value: "1",
          label: "上架",
        },
        {
          value: "2",
          label: "下架",
        },
      ],
      options2: [
        {
          value: "111",
          label: "请选择",
        },
        {
          value: "1",
          label: "批量上架",
        },
        {
          value: "2",
          label: "批量下架",
        },
        {
          value: "3",
          label: "删除",
        },
      ],
      type: "",
      sonObj: {},
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    value1(n, o) {
      if (n == 111) {
        this.value1 = "";
      }
      this.type = this.value1;
    },
    value2(n, o) {
      if (n == 111) {
        this.value2 = "";
      }
    },
  },
  //方法集合
  methods: {
    // 删除单个商品
    detailGoods(index, row) {
      this.deleteGoods(this.token, row.id);
    },
    // 删除商品接口
    deleteGoods(token, ids) {
      this.$confirm("确认删除选中商品吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteGoods(token, ids).then((res) => {
            if (res.data.status) {
              this.$message({
                type: "success",
                message: "删除成功!",
                onClose: (res) => {
                  this.getShopList(
                    this.token,
                    this.currentPage,
                    this.limit,
                    6,
                    "",
                    "",
                    this.topInputList[0].text,
                    this.topInputList[1].text,
                    this.type,
                    this.goods_cat_id,
                    ""
                  );
                },
              });
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 编辑商品
    handleEdit(index, row) {
      this.sonObj = JSON.parse(JSON.stringify(row));
      if (this.sonObj.marketable == 1) {
        this.$message.warning("上架时不能编辑");
        return;
      }
      this.allFlag = false;
      this.bianjiFlag = true;
    },
    // 返回商品管理
    back() {
      this.allFlag = true;
      this.bianjiFlag = false;
      this.addFlag = false;
      this.sonObj = {};
      this.getShopList(
        this.token,
        this.currentPage,
        this.limit,
        6,
        "",
        "",
        this.topInputList[0].text,
        this.topInputList[1].text,
        this.type,
        this.goods_cat_id,
        ""
      );
    },
    // 添加商品
    addGood() {
      this.allFlag = false;
      this.addFlag = true;
    },
    // 选择商品tab
    handleClick(tab, event) {
      if (tab.index == 0) {
        this.type = "";
      } else {
        this.type = tab.index;
      }
      this.getShopList(
        this.token,
        this.currentPage,
        this.limit,
        6,
        "",
        "",
        this.topInputList[0].text,
        this.topInputList[1].text,
        this.type,
        this.goods_cat_id,
        ""
      );
    },
    // 单个上下架
    switchChange(row) {
      let type = "";
      if (row.marketable == 1) {
        type = "up";
      } else if (row.marketable == 2) {
        type = "down";
      }
      let list = row.id;
      console.log(JSON.stringify(list), list);
      this.up_down(this.token, list, type);
    },
    // 商品状态
    opctionchangeOne(e) {},
    // 批量操作
    opctionchangeOne2() {
      if (this.multipleSelection.length <= 0) {
        this.$message("请先选择要操作的数据");
        return;
      }
      if (this.value2 == 111) {
        //'请选择'
      }
      if (this.value2 == 1) {
        //'上架'
        let ids = "";
        this.multipleSelection.forEach((item, index) => {
          ids += item.id + ",";
        });
        ids = ids.substr(0, ids.length - 1);
        this.up_down(this.token, ids, "up");
        this.getShopList(
          this.token,
          this.currentPage,
          this.limit,
          6,
          "",
          "",
          this.topInputList[0].text,
          this.topInputList[1].text,
          this.type,
          this.goods_cat_id,
          ""
        );
      }
      if (this.value2 == 2) {
        //'下架'
        let ids = "";
        this.multipleSelection.forEach((item, index) => {
          ids += item.id + ",";
        });
        ids = ids.substr(0, ids.length - 1);
        this.up_down(this.token, ids, "down");
        this.getShopList(
          this.token,
          this.currentPage,
          this.limit,
          6,
          "",
          "",
          this.topInputList[0].text,
          this.topInputList[1].text,
          this.type,
          this.goods_cat_id,
          ""
        );
      }
      if (this.value2 == 3) {
        //'删除'
        let ids = "";
        this.multipleSelection.forEach((item, index) => {
          ids += item.id + ",";
        });
        ids = ids.substr(0, ids.length - 1);
        this.deleteGoods(this.token, ids);
      }
      this.value2 = "";
    },
    // 上下架接口
    up_down(token, ids, type) {
      up_down(token, ids, type).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "操作成功",
            type: "success",
          });
        } else {
          this.$message.error("操作失败");
        }
      });
    },
    // 选中的用户
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 每页多少条
    handleSizeChange(val) {
      this.limit = val;
      this.getShopList(
        this.token,
        this.currentPage,
        this.limit,
        6,
        "",
        "",
        this.topInputList[0].text,
        this.topInputList[1].text,
        this.type,
        this.goods_cat_id,
        ""
      );
    },
    // 第几页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getShopList(
        this.token,
        this.currentPage,
        this.limit,
        6,
        "",
        "",
        this.topInputList[0].text,
        this.topInputList[1].text,
        this.type,
        this.goods_cat_id,
        ""
      );
    },
    // 获取用户信息接口
    getShopList(
      token,
      page,
      limit,
      goods_type_id,
      goods_brand_id,
      marketable,
      name,
      bn,
      status,
      goods_cat_id,
      materials
    ) {
      this.loading = true;
      goodSort(sessionStorage.getItem("token"), 3, "").then((res) => {
        if (res.data.status) {
          this.fenleiList = res.data.data;
          // this.fenleiList.forEach((item, index) => {
          //   console.log(item);
          //   item.child.forEach((item2, index2) => {
          //     if (item2.id == this.fatherObj.goods_cat_id) {
          //       this.selectfenleiList[0] = item.id;
          //       this.selectfenleiList[1] = item2.id;
          //     }
          //   });
          // });
        } else {
          this.$message.error(res.data.msg);
        }
      });

      goodsList(
        token,
        page,
        limit,
        goods_type_id,
        goods_brand_id,
        marketable,
        name,
        bn,
        status,
        goods_cat_id,
        "",
        materials
      )
        .then((res) => {
          if (res.data.status) {
            this.tableData = res.data.data.data;
            this.total = res.data.data.count;
            this.tableData.forEach((item) => {
              item.aimages = [];
              item.aimages.push(this.imgHeader + item.images);
            });

            let timer = setTimeout(() => {
              this.loading = false;
              clearTimeout(timer);
            }, 400);
          } else {
            if (res.data.msg == "token失效,请重新进行登录") {
              this.$router.push("/login");
            }
            if (res.data.msg == "此账号没有权限") {
              this.$message.error(res.data.msg);
              this.loading = false;
            }
            let timer = setTimeout(() => {
              this.$message.error(res.data.msg);
            }, 1000);
          }
        })
        .catch((err) => {
          console.log(err.message);
        });
    },
    brandList(token, page, limit, name, type) {
      this.loading = true;
      brandList(token, page, limit, name, type).then((res) => {
        // console.log(res.data)
        if (res.data.status) {
          this.brandOption = res.data.data.data;
          // this.total = res.data.data.count;
          // this.tableData.forEach((item) => {
          //   item.aavatar = [];
          //   if (item.logo) {
          //     item.aavatar.push("https://bjsf.bjsky.top" + item.logo);
          //   }
          // });
          let timer = setTimeout(() => {
            this.loading = false;
            clearTimeout(timer);
          }, 400);
        } else {
          if (res.data.msg == "token失效,请重新进行登录") {
            this.$router.push("/login");
          }
          this.loading = false;
          this.$message.error(res.data.msg);
          // let timer = setTimeout(()=>{
          //   this.$message.error('错误，请刷新');
          // },5000)
        }
      });
    },
    // 确定搜索btn
    search() {
      console.log(this.topInputList[0].text);
      this.currentPage = 1;
      this.getShopList(
        this.token,
        this.currentPage,
        this.limit,
        6,
        this.goods_brand_id,
        "",
        this.topInputList[0].text,
        this.topInputList[1].text,
        this.type,
        this.goods_cat_id,
        ""
      );
    },
    reset() {
      // this.goods_type_id = "";
      (this.topInputList[0].text = ""),
        (this.topInputList[1].text = ""),
        (this.goods_cat_id = "");
      this.goods_brand_id = "";
      this.getShopList(
        this.token,
        this.currentPage,
        this.limit,
        6,
        "",
        "",
        "",
        "",
        this.type,
        this.goods_cat_id,
        ""
      );
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // this.toAdd();
    this.getShopList(
      this.token,
      1,
      this.limit,
      6,
      "",
      "",
      "",
      "",
      "",
      this.goods_cat_id,
      ""
    );
    this.brandList(this.token, 1, 1000, "", 3);
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
  <style scoped >
.slelctBox {
  margin: 0 10px;
}

.everyBox {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.header .span {
  font-size: initial;
}

#app {
  width: 100%;
}

/deep/.header {
  background: white !important;
  box-shadow: 0 5px 10px #ddd;
  min-height: 40px;
  display: flex;
  padding: 10px;
  flex-wrap: wrap;
  align-items: center;
}

.top-input {
  width: 150px;
  margin-right: 20px;
}

/deep/.el-table th.el-table__cell > .cell {
  text-align: center;
}

/deep/.el-table .cell.el-tooltip {
  text-align: center;
}

/deep/.el-table--border .el-table__cell:first-child .cell {
  text-align: center;
}

/deep/ .el-tabs--border-card > .el-tabs__content {
  padding: 0;
}

.caozuo {
  display: flex;
  align-items: center;
}

.body {
  margin: 20px 0;
}
</style>
  